import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutterapp/common/constant/API.dart';
import 'package:flutterapp/common/util/dialog_utils.dart';
import 'package:flutterapp/common/util/toast_utils.dart';
import 'package:flutterapp/http/http_utils.dart';
import 'package:flutterapp/me/service/me_service.dart';
import 'package:flutterapp/system/entity/app_check_entity.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:r_upgrade/r_upgrade.dart';

class MeServiceImpl extends MeService {
  static MeServiceImpl? _instance;

  /// 版本升级提示内容
  String _updateContent = '';

  static MeServiceImpl getInstance() {
    if (_instance == null) _instance = MeServiceImpl._();
    return _instance!;
  }

  MeServiceImpl._();

  @override
  Future<AppCheckEntity?> appCheck() {
    return HttpUtils.getInstance().post<AppCheckEntity>(
      API.appCheck,
      options: Options()
        ..headers = {
          'baseUrl': API.pgyerBaseUrl,
        },
      queryParameters: {
        '_api_key': 'cd5a3a29a9eed4a3006665846e58e074',
        'appKey': 'd73185f4978436484dac5df7f04accb3',
      },
    );
  }

  /// 自动检测下载安装
  Future<void> autoCheckUpdate(BuildContext context) async {
    try {
      // 请求后台数据
      AppCheckEntity? appCheckEntity = await appCheck();
      // 获取本地包的数据
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      //远程的版本号不同于本地，且版本编号大于本地
      int localBuildNo = int.tryParse(packageInfo.buildNumber) ?? 0;
      int originBuildNo =
          int.tryParse(appCheckEntity?.data?.buildVersionNo ?? '') ?? 0;
      // 设置弹窗提示内容
      String updateContent =
          "更新内容:\n${appCheckEntity?.data?.buildUpdateDescription ?? ''}\n\n";
      String versionContent =
          "版本: ${packageInfo.version} → ${appCheckEntity?.data?.buildVersion}\n";
      String fileSize =
          "大小: ${((int.tryParse(appCheckEntity?.data?.buildFileSize ?? "") ?? 0) / (1024 * 1024)).toStringAsFixed(1)}M";
      _updateContent = "$updateContent$versionContent$fileSize";

      // 更新逻辑(版本名称不同且远程版本编号大于本地版本编号)
      if (packageInfo.version != appCheckEntity?.data?.buildVersion &&
          originBuildNo > localBuildNo) {
        showEasyDialog(
          context: context,
          title: "版本更新",
          type: EasyDialogType.NormalTwoRowBtn,
          content: _updateContent,
          contentTextAlign: TextAlign.start,
          leftOrTopBtnText: '忽略此版本',
          rightOrBottomBtnText: '确定升级',
          leftOrTopOnTap: (context) => Navigator.pop(context),
          rightOrBottomOnTap: (context) {
            Navigator.pop(context);
            RUpgrade.upgrade(
              appCheckEntity?.data?.downloadUrl ?? '',
              fileName: 'wan-android-release.apk',
            );
          },
        );
      } else {
        shortToast('当前已是最新版本!');
      }
    } catch (e) {
      shortToast(e.toString());
    }
  }

  /// 检测是否有更新
  Future<bool> checkNeedUpdate() async {
    try {
      // 请求后台数据
      AppCheckEntity? appCheckEntity = await appCheck();
      // 获取本地包的数据
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      //远程的版本号不同于本地，且版本编号大于本地
      int localBuildNo = int.tryParse(packageInfo.buildNumber) ?? 0;
      int originBuildNo =
          int.tryParse(appCheckEntity?.data?.buildVersionNo ?? '') ?? 0;

      // 更新逻辑(版本名称不同且远程版本编号大于本地版本编号)
      return packageInfo.version != appCheckEntity?.data?.buildVersion &&
          originBuildNo > localBuildNo;
    } catch (e) {
      shortToast(e.toString());
      return false;
    }
  }
}
